
#include "Base.h"
#include "Multi.h"

VOID Multi(BIGVALUE num1, ULONG num2, BIGVALUE* pbvResult)
{
    BYTE ucFirst = num2 & 0xff;
    BYTE ucSecond = (num2>>8)&0xff;
    BYTE ucThird = (num2>>16)&0xff;
    BYTE ucFourth = (num2>>24)&0xff;
    BIGVALUE bvTemp1 = {0};
    BIGVALUE bvTemp2 = {0};
    BIGVALUE bvResult = {0};

    MultiBigValueWithByte(num1, ucFirst, &bvResult);
    if(0 != ucSecond)
    {
        MultiBigValueWith0x100(num1, &bvTemp1);
        MultiBigValueWithByte(bvTemp1, ucSecond, &bvTemp2);
        Add(bvResult, bvTemp2, &bvResult);
    }
    if(0 != ucThird)
    {
        MultiBigValueWith0x100(bvTemp1, &bvTemp1);
        MultiBigValueWithByte(bvTemp1, ucThird, &bvTemp2);
        Add(bvResult, bvTemp2, &bvResult);
    }
    if(0 != ucFourth)
    {
        MultiBigValueWith0x100(bvTemp1, &bvTemp1);
        MultiBigValueWithByte(bvTemp1, ucFourth, &bvTemp2);
        Add(bvResult, bvTemp2, &bvResult);
    }

    ResetBigValue(&bvTemp1);    
    CopyBigValue(bvResult, pbvResult);
}

VOID MultiBigValueWithByte(BIGVALUE num1, BYTE ucNum2, BIGVALUE* pbvResult)
{
    ULONG ulLoop = 0;
    ULONG ulTemp = 1;
    ULONG ulHighValue = 0;
    BYTE* pucNum1 = NULL;
    BYTE* pucResult = NULL;
    BIGVALUE bvTemp = {0};

    NewBigValue(&bvTemp, num1.ulByteCount + 1);
    for(ulLoop = 0; ulLoop < num1.ulByteCount; ulLoop++)
    {
        pucNum1 = num1.pucBuff + ulLoop;
        pucResult = bvTemp.pucBuff + ulLoop;
        ulTemp = (*pucNum1) * ucNum2;
        ulTemp += ulHighValue;
        *pucResult = (BYTE)(ulTemp & 0xFF);
        ulHighValue = (ulTemp >> 8) & 0xFF;
    }
    if(0 != ulHighValue)
    {
        pucResult = bvTemp.pucBuff + (bvTemp.ulByteCount - 1);
        *pucResult = ulHighValue;
    }
    else
    {
        bvTemp.ulByteCount--;
    }
    CopyBigValue(bvTemp, pbvResult);
}

VOID MultiBigValueWith0x100(BIGVALUE num1, BIGVALUE* pbvResult)
{
    BIGVALUE bvTemp = {0};
    BYTE* pucSrc = NULL;
    BYTE* pucDst = NULL;
    NewBigValue(&bvTemp, num1.ulByteCount + 1);

    pucSrc = num1.pucBuff;
    pucDst = bvTemp.pucBuff + 1;

    Memcpy(pucDst, pucSrc, num1.ulByteCount);

    CopyBigValue(bvTemp,pbvResult);
}

